package com.dpiinc.TechPage.pen.adapter;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.dpiinc.TechPage.R;
import com.dpiinc.TechPage.model.jbean.NoteLabelEditBean;
import com.dpiinc.TechPage.pen.dialog.InputDialog;
import com.dpiinc.TechPage.pen.dialog.OneButtonDialog;
import com.dpiinc.TechPage.room.RoomAiWriterDatabase;
import com.dpiinc.TechPage.room.bean.LabelEntity;
import com.dpiinc.TechPage.room.bean.NoteEntity;
import com.dpiinc.TechPage.room.dao.LabelDao;
import com.dpiinc.TechPage.room.dao.NoteDao;
import com.dpiinc.TechPage.user.logic.NoteLabelLogic;
import com.dpiinc.TechPage.user.setting.LabelAvtivity;
import com.dpiinc.TechPage.widget.CommDialog;

import java.util.List;

/**
 * Created by hu489_000 on 2018-07-22.
 */

public class LabelBaseAdapter extends BaseAdapter {
    private static final String TAG = "LabelBaseAdapter";
    private  String locale;
    private AppCompatActivity mContext;
    private List<LabelEntity> list;
    private boolean isEdit = false;


    public LabelBaseAdapter(AppCompatActivity mContext, List<LabelEntity> list) {
        this.mContext = mContext;
        this.list = list;
        locale = mContext.getResources().getConfiguration().locale.getLanguage();
    }

    //获取当前items项的大小，也可以看成是数据源的大小
    @Override
    public int getCount() {
        return list.size();
    }

    //根据item的下标获取到View对象
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    //获取到items的id
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }


    //根据传入item的下标，获取到view对象
    /*
     * int position,      表示item所在listView中的下标，也是在数据源中下标所对应的数据
     * View convertView,  缓存机制，当一些item项滑出屏幕的时候，会创建新的View对象，这样会使得内存资源占据，
     *                                  所以使用convertView判断是否为空，如果为空的说明item没有滑出，需要创建新的view对象
     *                          如果不为空，说明已经滑出类屏幕所以使用convertView ，view = convertView，
     *                                  可以把convert 理解为滑出的view对象
     * ViewGroup parent   视图组对象，即 表示当前绘制的items项所属的ListView对象。
     * */
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View view = null;

        //获取填充器对象，这个对象可以帮助我们绘制出items项，获取方式有多种：
        //LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LayoutInflater inflater = LayoutInflater.from(mContext);
            /*
            调用打气筒中的 inflate(int resource, ViewGroup root) 方法
            第一个参数是一个布局文件对象，通过这个布局文件，inflater会在这布局文件中绘制items项
            第二个参数是需不需要将第一个参数中的那个布局文件嵌入到另外一个布局文件中。如果要写上布局文件的id，如果不需要直接写null
            */
        view = inflater.inflate(R.layout.label_item, null);
        final LabelEntity u = list.get(position);//通过回调这个方法传过来的position参数获取到指定数据源中的对象
        //找到布局文件中的控件
//        ImageView pic = (ImageView) view.findViewById(R.id.items_pic);
        TextView name = (TextView) view.findViewById(R.id.label_name);
//        pic.setImageResource(u.getPic());//从数据源中获取头像 设置到布局文件的ImageView控件中。
        analysisLanguage(u,name);
        ImageView label_delete = (ImageView) view.findViewById(R.id.label_delete);
        label_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final CommDialog.Builder builder = new CommDialog.Builder();
                builder.setTitle(mContext.getResources().getString(R.string.label_delete_dialog_title))
                        .setMessage(mContext.getResources().getString(R.string.label_name_delete))
                        .setLeftButton(mContext.getResources().getString(R.string.comm_dialog_btn_cancel), null)
                        .setRightButton(mContext.getResources().getString(R.string.comm_dialog_btn_ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (position >= 0 && position < list.size()) {

                                    final LabelEntity label = list.get(position);
                                    NoteLabelLogic.noteLabelEdit(mContext, NoteLabelLogic.EDITTYPE_DELETE, String.valueOf(label.getId()), u.getContent(), new NoteLabelLogic.OnEditSuccess() {
                                        @Override
                                        public void onHandleSuccess(NoteLabelEditBean baseBean) {

                                            LabelDao labelDao = RoomAiWriterDatabase.getInstance(mContext).labelDao();
                                            labelDao.delete(label);
                                            ((LabelAvtivity) mContext).notifyDataSetChanged();
                                        }
                                    });
                                    dialog.dismiss();
                                    deleteLabelsInNote(label);
                                }
                            }
                        });
                builder.build().show(mContext.getSupportFragmentManager());
            }
        });
        ImageView label_edit = (ImageView) view.findViewById(R.id.label_edit);
        label_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputDialog.ShowDialog(mContext, mContext.getResources().getString(R.string.rename_label), u.getContent(), new InputDialog.OnClickEditListener() {
                    @Override
                    public void onClickEdit(final String text) {
                        Log.d(TAG, "onClickEdit  text=" + text);
                        if (!TextUtils.isEmpty(text)) {
                            final LabelDao labelDao = RoomAiWriterDatabase.getInstance(mContext).labelDao();
                            LabelEntity le = labelDao.getLabelByContent(text);
                            if (le != null) {

                                OneButtonDialog.ShowDialog(mContext, null, mContext.getResources().getString(R.string.label_name_exist), true, null);

                                return;
                            }


                            LabelEntity label = list.get(position);
                            NoteLabelLogic.noteLabelEdit(mContext, NoteLabelLogic.EDITTYPE_EDIT, String.valueOf(label.getId()), text, new NoteLabelLogic.OnEditSuccess() {
                                @Override
                                public void onHandleSuccess(NoteLabelEditBean baseBean) {

                                    LabelEntity updateLabel = new LabelEntity(baseBean.getLabelId(), text);
                                    labelDao.update(updateLabel);
                                    ((LabelAvtivity) mContext).notifyDataSetChanged();
                                    updateLabelsInNote(updateLabel);
                                }
                            });

                        } else {
                            OneButtonDialog.ShowDialog(mContext, null, mContext.getResources().getString(R.string.label_name_not_null), true, null);
                        }
                    }
                });
            }
        });
        if (isEdit) {
            label_delete.setVisibility(View.VISIBLE);
            label_edit.setVisibility(View.VISIBLE);
        } else {
            label_delete.setVisibility(View.GONE);
            label_edit.setVisibility(View.GONE);
        }
        return view;
    }

    @SuppressLint("SetTextI18n")
    private void analysisLanguage(LabelEntity u, TextView name) {
        if ("会议纪要".equals(u.getContent())) {
            name.setText(mContext.getResources().getString(R.string.Meeting_Minutes));
        } else if ("工作日志".equals(u.getContent())){
            name.setText(mContext.getResources().getString(R.string.Work_log));
        }else if ("工作周报".equals(u.getContent())){
            name.setText(mContext.getResources().getString(R.string.Weekly_work_report));
        }else if ("待办事项".equals(u.getContent())){
            name.setText(mContext.getResources().getString(R.string.to_do_list));
        } else if ("读书笔记".equals(u.getContent())) {
            name.setText(mContext.getResources().getString(R.string.reading_notes));
        } else {
            name.setText(u.getContent());
        }
        Log.e(TAG, "会议纪要=========》" + u.getContent());
       // name.setText(u.getContent());//从数据源中获取名字 设置到布局文件的TextView控件中。
    }

    public void setList(List<LabelEntity> list) {
        this.list = list;
    }

    public void setEdit(boolean edit) {
        this.isEdit = edit;
        ((LabelAvtivity) mContext).notifyDataSetChanged();
    }

    private void updateLabelsInNote(LabelEntity newLabel) {
        NoteDao noteDao = RoomAiWriterDatabase.getInstance(mContext).noteDao();
        List<NoteEntity> noteList = noteDao.getNotes();
        for (NoteEntity note : noteList) {
            if (note.getLabel() == null) {
                continue;
            }
            boolean isUpdated = false;
//            for (LabelEntity label : note.getLabel()) {
//                if (label.getId().equals(newLabel.getId())) {
//                    label.setContent(newLabel.getContent());
//                    isUpdated = true;
//                }
//            }
            for (int i = 0; i < note.getLabel().size(); i++) {
                if (note.getLabel().get(i).getId().equals(newLabel.getId())) {
                    note.getLabel().get(i).setContent(newLabel.getContent());
                    isUpdated = true;
                }
                if (!list.contains(note.getLabel().get(i))) {
                    note.getLabel().remove(i);
                    i--;
                    isUpdated = true;
                }
            }
            if (isUpdated) {
                //更新时间做微小调整，触发笔记列表刷新，但又不改变笔记列表排序
                note.setModifyTime(note.getModifyTime() + 1);
                noteDao.update(note);
            }
        }
    }

    private void deleteLabelsInNote(LabelEntity deletedLabel) {
        NoteDao noteDao = RoomAiWriterDatabase.getInstance(mContext).noteDao();
        List<NoteEntity> noteList = noteDao.getNotes();
        for (NoteEntity note : noteList) {
            if (note.getLabel() == null) {
                continue;
            }
            boolean isUpdated = false;
            for (int i = 0; i < note.getLabel().size(); ) {
                LabelEntity label = note.getLabel().get(i);
                if (label.getId().equals(deletedLabel.getId())) {
                    note.getLabel().remove(label);
                    isUpdated = true;
                } else {
                    i++;
                }
            }
            if (isUpdated) {
                //更新时间做微小调整，触发笔记列表刷新，但又不改变笔记列表排序
                note.setModifyTime(note.getModifyTime() + 1);
                noteDao.update(note);
            }
        }
    }
}

